unit ORM.Drive.Connection;

interface

uses
  System.SysUtils, Data.DBXDynalink, Vcl.Dialogs, Data.DbxFirebird, Data.DbxMSSQL, Data.DBXCommon,
  ORM.Drive.Connection.Firebird, ORM.Drive.Connection.MSSQL, ORM.Enumerators;


type
  TConnectionDBX = class
  private
    FDriveFirebird : TDriveFirebird;
    FDriveMSSQL : TDriveMSSQL;
    FConnection: TDBXConnection;
    FTransactionCount: Integer;
    class var FConnectionDBX: TConnectionDBX;
    constructor Create;
    procedure Connect(const pTypeConnection : TTypeConnection);
  public
    property ContagemTransacao : Integer read FTransactionCount write FTransactionCount;
    function DBXConnection: TDBXConnection;
    destructor Destroy; override;
    procedure Disconnect;
    class function GetConnection(pTypeConnection : TTypeConnection = tpFirebird): TConnectionDBX;
  end;


implementation

uses
  Vcl.Forms;

{ TConnectionDBX }

procedure TConnectionDBX.Connect(const pTypeConnection : TTypeConnection);
var
  AppName : string;
begin
  AppName := Copy(ExtractFileName(Application.ExeName), 1, Length(ExtractFileName(Application.ExeName)) - 4);
  case pTypeConnection of
    tpFirebird :
    begin
      FDriveFirebird := TDriveFirebird.Create;
      FConnection := TDBXConnectionFactory.GetConnectionFactory.GetConnection(AppName, FDriveFirebird.UserName ,
                                                                              FDriveFirebird.Password);
    end;
    tpMSSQL :
    begin
      FDriveMSSQL := TDriveMSSQL.Create;
      FConnection := TDBXConnectionFactory.GetConnectionFactory.GetConnection(AppName, FDriveMSSQL.UserName,
                                                                              FDriveMSSQL.Password);
    end;
  end;
end;

constructor TConnectionDBX.Create;
begin
  inherited create;
end;

function TConnectionDBX.DBXConnection: TDBXConnection;
begin
  Result := FConnection;
end;

procedure TConnectionDBX.Disconnect;
begin
  FConnection.Close;
end;

destructor TConnectionDBX.Destroy;
begin
  Disconnect;
  if Assigned(FDriveFirebird) then FreeAndNil(FDriveFirebird);
  if Assigned(FDriveMSSQL) then FreeAndNil(FDriveMSSQL);
  FreeAndNil(FConnection);
  inherited;
end;

class function TConnectionDBX.GetConnection(pTypeConnection : TTypeConnection = tpFirebird) : TConnectionDBX;
begin
  if not Assigned(FConnectionDBX) then
  begin
    FConnectionDBX := TConnectionDBX.Create;
    FConnectionDBX.Connect(pTypeConnection);
  end;
  Result := FConnectionDBX;
end;

end.
